#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "esp_system.h"
#include "esp_wifi.h"
#include "esp_event.h"
#include "esp_log.h"
#include "nvs_flash.h"
#include "lwip/err.h"
#include "lwip/sockets.h"
#include "lwip/sys.h"
#include "lwip/netdb.h"
#include "serial.h"

// 配置你的WiFi信息
#define WIFI_SSID      "DLINK"
#define WIFI_PASS      "zhuzhu@2018"

//static const char *TAG = "TCP_SERVER";

static EventGroupHandle_t wifi_event_group;
const int WIFI_CONNECTED_BIT = BIT0;

static void wifi_event_handler(void* arg, esp_event_base_t event_base, 
                              int32_t event_id, void* event_data)
{
    if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
        esp_wifi_connect();
    } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
        esp_wifi_connect();
        xEventGroupClearBits(wifi_event_group, WIFI_CONNECTED_BIT);
    } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
        ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data;
        print("Wifi IP: %d.%d.%d.%d\r\n",IP2STR(&event->ip_info.ip));
        xEventGroupSetBits(wifi_event_group, WIFI_CONNECTED_BIT);
    }
}

void wifi_init_sta(void)
{
    wifi_event_group = xEventGroupCreate();

    ESP_ERROR_CHECK(esp_netif_init());
    ESP_ERROR_CHECK(esp_event_loop_create_default());
    esp_netif_create_default_wifi_sta();

    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    ESP_ERROR_CHECK(esp_wifi_init(&cfg));

    esp_event_handler_instance_t instance_any_id;
    esp_event_handler_instance_t instance_got_ip;
    ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT,
                                                      ESP_EVENT_ANY_ID,
                                                      &wifi_event_handler,
                                                      NULL,
                                                      &instance_any_id));
    ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT,
                                                      IP_EVENT_STA_GOT_IP,
                                                      &wifi_event_handler,
                                                      NULL,
                                                      &instance_got_ip));

    wifi_config_t wifi_config = {
        .sta = {
            .ssid = WIFI_SSID,
            .password = WIFI_PASS,
            .threshold.authmode = WIFI_AUTH_WPA2_PSK
        },
    };
    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
    ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config));
    ESP_ERROR_CHECK(esp_wifi_start());
}

struct ServerStruct
{
    int port;
    void (*accept)(int sock);
};

void tcp_server_task(void *pvParameters)
{
    char rx_buffer[128];
    char addr_str[128];
    struct sockaddr_in server_addr;
    struct sockaddr_in client_addr;
    socklen_t client_addr_len = sizeof(client_addr);
    struct ServerStruct* pss = pvParameters;

    // 创建TCP套接字
    int listen_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
    if (listen_sock < 0) {
        print("Failed to create socket. Error %d\r\n", errno);
        vTaskDelete(NULL);
        return;
    }
    
    // 绑定套接字
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_addr.sin_port = htons(pss->port);
    
    int err = bind(listen_sock, (struct sockaddr *)&server_addr, sizeof(server_addr));
    if (err != 0) {
        print("Failed to bind socket. Error %d\n", errno);
        close(listen_sock);
        vTaskDelete(NULL);
        return;
    }
    
    // 开始监听
    err = listen(listen_sock, 1);
    if (err != 0) {
        print("Failed to listen on socket. Error %d\r\n", errno);
        close(listen_sock);
        vTaskDelete(NULL);
        return;
    }
    
    print("TCP server started on port %d\n", pss->port);

    while (1) {
        // 接受客户端连接
        int client_sock = accept(listen_sock, (struct sockaddr *)&client_addr, &client_addr_len);
        if (client_sock < 0) {
            print("Failed to accept connection. Error %d\r\n", errno);
            continue;
        }
        // 打印客户端IP
        inet_ntoa_r(client_addr.sin_addr, addr_str, sizeof(addr_str) - 1);
        print("Client connected from %s\r\n", addr_str);
        pss->accept(client_sock);
    }
    
    close(listen_sock);
    vTaskDelete(NULL);
}

void init_wifi_sta()
{
    // 初始化WiFi
    wifi_init_sta();
    // 等待WiFi连接
    xEventGroupWaitBits(wifi_event_group, WIFI_CONNECTED_BIT, false, true, portMAX_DELAY);
}

static struct ServerStruct ss;

void create_server(int port,void (*accept)(int sock))
{
    ss.port = port;
    ss.accept = accept;
    xTaskCreate(tcp_server_task, "tcp_server", 2048, &ss, 5, NULL);
}
